import { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { ILoadingInstance } from "element-plus/lib/el-loading/src/loading.type";

import { Request, ResProps } from "./axios";
import { localStorageKey } from "@/global";

enum ReturnStatus {
  notFound = 404,
}

const returnMessage = {
  [ReturnStatus.notFound]: "404未找到资源",
};

const request = new Request({
  baseURL: process.env.VUE_APP_API_URL || "",
  timeout: 1000,
});
//request.axiosA.defaults.headers['x-icode'] = 'EF549E5DDD2E177F';
let loading: ILoadingInstance;
//拦截器
request.instance.interceptors.request.use(
  (result: AxiosRequestConfig) => {
    // loading = ElLoading.service({
    //   lock: true,
    //   text: "正在请求数据。。。。",
    //   background: "rgba(0,0,0,0.5)",
    // });
    //加token
    if (localStorage.getItem(localStorageKey)) {
      result.headers.Authorization = `Ber ${
        localStorage.getItem(localStorageKey) as string
      }`;
    }

    return result;
  },
  (error) => {
    ElMessage({
      type: "error",
      message: "发送失败",
    });
    console.log("error", error);
    //loading.close();
    return error;
  }
);
//拦截处理不是200的数据
request.instance.interceptors.response.use(
  (result: AxiosResponse<ResProps>) => {
    //loading.close();
    return result;
  },
  (err: { response: ResProps }) => {
    // message.warning(err.response.data.message);
    //拦截错误信息
    const status = err.response.status;
    //loading.close();
    switch (status) {
      case ReturnStatus.notFound:
        ElMessage({
          type: "error",
          message: returnMessage[status],
        });
        break;
      default:
        ElMessage({
          type: "error",
          message: "请求失败",
        });
    }
    console.log("err", err);
    return Promise.reject(err);
  }
);

export default request;
